package mfuny.ggongal.admin.gcm;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import mfuny.ggongal.admin.Server;
import mfuny.ggongal.admin.debug.Debug;

import org.springframework.web.servlet.ModelAndView;

import com.ibatis.sqlmap.client.SqlMapClient;

public class GCMService {
	SqlMapClient sqlMapper;
	ModelAndView mav;
	
	public GCMService() throws Exception {
		sqlMapper = Server.getSqlMapper();
		mav = new ModelAndView();
	}
	
	//gcm 현황.
	public ModelAndView gcm() throws Exception {
		mav.clear();
		mav.setViewName("/gcm/gcm.ga");
		return mav;
	}
	
	//gcm 보내기 처리.
	@SuppressWarnings("unchecked")
	public ModelAndView sendGcm(String content) throws Exception {
		try {
			content = URLEncoder.encode(content, "utf-8");
			
			List<String> allId = sqlMapper.queryForList("user_selectAllPid", null);
			List<List<String>> pushList = getListForPush(allId);
			List<HashMap<String, Object>> resultList = new ArrayList<HashMap<String, Object>>();
			int success = 0;
			int total = 0;
			int failed = 0;
			
			for(int i = 0; i < pushList.size(); i++) {
				HashMap<String, Object> tempResult = new GCMSender().basicPush(pushList.get(i), content);
				resultList.add(tempResult);
			}
			for(int i = 0; i < resultList.size(); i++) {
				success += (Integer)resultList.get(i).get("success");
				total += (Integer)resultList.get(i).get("total");
				failed += (Integer)resultList.get(i).get("failed");
			}
			HashMap<String, Object> resultMap = new HashMap<String, Object>();
			resultMap.put("success", success);
			resultMap.put("total", total);
			resultMap.put("failed", failed);
			
			mav.clear();
			mav.setViewName("/gcm/sendGcm");
			mav.addObject("resultMap", resultMap);
			
		} catch ( Exception e ) {
			Debug.toDebugFile(e, "sendGcm");
		}
		
		return mav;
	}
	
	//gcm 용 아이디 분할(1000개씩).
	public List<List<String>> getListForPush(List<String> allId) {
		List<List<String>> pushList = new ArrayList<List<String>>();
		
		int pushCount = (int) Math.ceil(allId.size() / 1000.0f);
		
		for(int i = 0; i < pushCount; i++) {
			List<String> tempList = null;
			if(i == pushCount - 1) {
				tempList = allId.subList(
					i * 1000, 
					allId.size()
				);
				
			} else {
				tempList = allId.subList(
					i == 0 ? 0 : i * 1000,
					i == 0 ? 1000 : (i + 1) * 1000
				);
			}
			
			pushList.add(tempList);
		}
		return pushList;
	}
}
